package com.hjy.attendance.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjy.attendance.cache.TeacherCache;
import com.hjy.attendance.context.IMContextHolder;
import com.hjy.attendance.dao.UserDao;
import com.hjy.attendance.entity.*;
import com.hjy.attendance.entity.Class;
import com.hjy.attendance.enums.ResultEnum;
import com.hjy.attendance.exception.ApiException;
import com.hjy.attendance.role.RoleType;
import com.hjy.attendance.service.ClassService;
import com.hjy.attendance.service.StudentService;
import com.hjy.attendance.service.TeacherService;
import com.hjy.attendance.service.UserService;
import com.hjy.attendance.util.BeanUtil;
import com.hjy.attendance.util.Common;
import com.hjy.attendance.util.JwtUtil;
import com.hjy.attendance.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * <p>标题:  Service 实现类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2020</p>
 *
 * @version: 1.0
 * @author: huangjunyu
 * @date 2020-04-18
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserDao, User> implements UserService {

    @Autowired
    StudentService studentService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    TeacherCache teacherCache;

    @Autowired
    ClassService classService;
    @Override
    public User loginByForm(User user) throws Exception{
        user.setPassword(Common.string2MD5(user.getPassword()));
        QueryWrapper<User> queryWrapper=new QueryWrapper<>(user);
        Optional<User> userOptional=Optional.ofNullable(this.baseDao.selectOne(queryWrapper));
        userOptional=userOptional.map(d-> {
            IMContextHolder.set(IMContextHolder.TOKEN, JwtUtil.sign(d.getUserName()));
            IMContextHolder.set(IMContextHolder.OPERATOR,d.getUserName());
            WebUtils.getCurrentSession().setAttribute(IMContextHolder.OPERATOR,d.getUserName());
            String permissionCode=d.getPermissionCode();
            String name="0".equals(permissionCode)?"管理员":("1".equals(permissionCode)?studentService.getById(d.getUserName()).getName():teacherService.getById(d.getUserName()).getName());
            d.setUserName(name);
            return d;
        });
        return userOptional.orElseGet(()->{
            JwtUtil.setGlobalEmptyToken();
            return null;
        });
    }

    @Override
    public Map<String,Object> refreshUserByToken() throws Exception {
        String userName=JwtUtil.decode(IMContextHolder.get(IMContextHolder.TOKEN));
        WebUtils.getCurrentSession().setAttribute(IMContextHolder.OPERATOR,userName);
        User user=this.baseDao.selectById(userName);
        String name="0".equals(user.getPermissionCode())?"管理员":("1".equals(user.getPermissionCode())?studentService.getById(user.getUserName()).getName():teacherService.getById(user.getUserName()).getName());
        Map<String,Object> map=BeanUtil.transBean2Map(user);
        map.put("userId",user.getUserName());
        map.put("userName",name);
        return map;
    }

    @Override
    public List<Map<String, Object>> getAllUsers() throws Exception {
        return this.baseDao.getAllUsers();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(Map<String,Object> user) throws ApiException {
        String password=Common.string2MD5(user.get("password").toString());
        String permissionCode=user.get("permissionCode").toString();
        String userName=user.get("userName").toString();
        User u=Optional.ofNullable(getById(userName)).orElse(null);
        if (u!=null){
           throw  new ApiException(ResultEnum.CUSTOMFAILURE,"该用户已经存在");
        }
        insert(User.builder().createdTime(new Date()).permissionCode(permissionCode).password(password).updateTime(new Date()).userName(userName).validFlag(1).build());
        String name=user.get("name").toString();
        if ("1".equals(permissionCode)){//学生
            String teacherId=user.get("teacherId").toString();
            Class c=classService.getById(user.get("classNo").toString());
            Student student=new Student();
            student.setAssistant(teacherId).setClassNo(c.getGuid()).setDepartmentNo(c.getDepartmentCode()).setGuid(userName)
                    .setMajorNo(c.getMajorCode()).setGradeNo(c.getGradeNo()).setName(name);
            studentService.insert(student);
        }else if("2".equals(permissionCode)){
            Teacher teacher=new Teacher();
            teacher.setGuid(userName).setName(name);
            teacherService.insert(teacher);
            teacherCache.clear();
        }
    }
}
